package com.launcher.wkang.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ShutDownService extends Service {
    private String TAG="ShutDownService";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        shutdown();
        return super.onStartCommand(intent, flags, startId);
    }
    private void shutdown() {
                try {

            //获得ServiceManager类
            Class<?> ServiceManager = Class
                    .forName("android.os.ServiceManager");

            //获得ServiceManager的getService方法
            Method getService = ServiceManager.getMethod("getService", java.lang.String.class);

            //调用getService获取RemoteService
            Object oRemoteService = getService.invoke(null,Context.POWER_SERVICE);

            //获得IPowerManager.Stub类
            Class<?> cStub = null;

            cStub = Class
                    .forName("android.os.IPowerManager$Stub");

            //获得asInterface方法
            Method asInterface = null;

            asInterface = cStub.getMethod("asInterface", IBinder.class);

            //调用asInterface方法获取IPowerManager对象
            Object oIPowerManager = null;

            oIPowerManager = asInterface.invoke(null, oRemoteService);

            //获得shutdown()方法
            Method shutdown = oIPowerManager.getClass().getMethod("shutdown",boolean.class,String.class,boolean.class);
            //调用shutdown()方法
            shutdown.invoke(oIPowerManager,false,"shutdown",false);
                    Log.d("ShutDownService","ShutDownService shutdown.invoke(=");

        } catch (ClassNotFoundException e) {
            Log.d("ShutDownService","ShutDownService ClassNotFoundException="+e.getCause().getMessage());
            e.printStackTrace();
        }catch (NoSuchMethodException e) {
            Log.d("ShutDownService","ShutDownService NoSuchMethodException="+e.getCause().getMessage());
            e.printStackTrace();
        }catch (IllegalAccessException e) {
            Log.d("ShutDownService","ShutDownService IllegalAccessException="+e.getCause().getMessage());
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            Log.d("ShutDownService","ShutDownService InvocationTargetException="+e.getCause().getMessage());
            e.printStackTrace();
        }
    }
    }
